from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from app.config import create_db_connection

add_customers_bp = Blueprint('add_customers', __name__)

@add_customers_bp.route('/add_customer')
def show_add_customer():
    return render_template('customer/add_customer.html')


# 处理客户提交请求的路由
@add_customers_bp.route('/submit_customer', methods=['POST'])
def submit_customer():
    # 获取前端提交的客户信息
    customer_name = request.form.get('customer_name')
    creditCode = request.form.get('creditCode')
    address = request.form.get('address')
    contactPerson = request.form.get('contactPerson')
    contactNumber = request.form.get('contactNumber')

    try:
        # 检查公司名称是否为空
        if not customer_name:
            response = {'success': False, 'message': '公司名称不能为空！'}
            return jsonify(response), 400

        # 读取数据库连接配置
        conn, cursor = create_db_connection()

        # 检查公司名称是否已存在
        query_sql = "SELECT * FROM customer_list WHERE customer_name = %s"
        cursor.execute(query_sql, (customer_name,))
        result = cursor.fetchone()
        if result:
            cursor.close()
            conn.close()
            response = {'success': False, 'message': '该公司名称已存在！'}
            return jsonify(response), 400

        # 执行插入操作将客户信息保存到数据库
        insert_sql = "INSERT INTO customer_list (customer_name, creditCode, address, contactPerson, contactNumber) VALUES (%s, %s, %s, %s, %s)"
        values = (customer_name, creditCode, address, contactPerson, contactNumber)
        cursor.execute(insert_sql, values)
        conn.commit()
        cursor.close()
        conn.close()

        # 返回成功响应
        response = {'success': True, 'message': '客户添加成功！'}
        return jsonify(response)
    except Exception as e:
        # 返回错误响应
        response = {'success': False, 'message': str(e)}
        return jsonify(response), 500
